package com.haiyou.data.game.base;

import java.util.Map;
import java.util.Set;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;

import org.springframework.util.ObjectUtils;

import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.haiyou.common.constants.ErrCode;
import com.haiyou.common.entity.PlayerEntity;
import com.haiyou.common.util.check.Assert;
import com.haiyou.data.common.accessor.redis.redisson.bucket.BucketAccessor;

/**
 * 
 * 玩家数据对象 基于玩家id查询
 * @author xingyuan
 * @Date 2023年6月26日 上午10:22:41
 */
public class BucketPlayerAccessor<E extends PlayerEntity<String>> extends BucketAccessor<E>{
	
	/**
	 * 基于玩家ID操作
	 * @param playerId
	 * @param remappingFunction
	 * @return
	 */
	public E compute(long playerId, BiFunction<? super String, ? super E, ? extends E> remappingFunction) {
		
		String key = GamePlayerModuleCaster.castPlayerIdTo(playerId, getValueClass()); 
		
		return super.compute(key, remappingFunction);
	}	
	
	
	/**
	 * 基于玩家ID 获取
	 * @param playerId
	 * @return
	 */
	public E get(long playerId) {
		
		String key = GamePlayerModuleCaster.castPlayerIdTo(playerId, getValueClass());
		
		return super.get(key);
	}
	
	/**
	 * 基于玩家id操作
	 * @param playerId
	 * @param mappingFunction
	 * @return
	 */
	public E get(long playerId,Function<? super String, ? extends E> mappingFunction) {
		String key = GamePlayerModuleCaster.castPlayerIdTo(playerId, getValueClass());
		return super.get(key,mappingFunction);
	}
	
	/**
	 * 从redis 中获取 基于玩家ID
	 * @param playerId
	 * @return
	 */
	public E getRedis(long playerId) {
		
		String key = GamePlayerModuleCaster.castPlayerIdTo(playerId, getValueClass());
		
		return super.getRedis(key);
	}
	
	
	/**
	 * 基于玩家ID 获取
	 * @param playerIds
	 * @return
	 */
	public Map<String, E> getAllByPlayerIds(Iterable<? extends Long> playerIds) {
		if(ObjectUtils.isEmpty(playerIds)) {
			return Maps.newHashMap();
		}
		Set<String> keySet = Sets.newHashSet();
		playerIds.forEach(key -> {
				keySet.add(GamePlayerModuleCaster.castPlayerIdTo(key, getValueClass()));
		});

		return super.getAll(keySet);
	}
	
	/**
	 * 基于玩家ID 删除
	 * @param playerIds
	 * @return
	 */
	public void removeAllByPlayerIds(Iterable<? extends Long> playerIds) {
		
		if(ObjectUtils.isEmpty(playerIds)) {
			return ;
		}
		Set<String> keySet = Sets.newHashSet();
		playerIds.forEach(key -> {
			keySet.add(GamePlayerModuleCaster.castPlayerIdTo(key, getValueClass()));
		});
		
		super.removeAll(keySet);
	}

	@Override
	public String generateKey() {
		Assert.isTrue(false, ErrCode.METHOD_NOT_SUPPORT);
		return null;
	}

	@Override
	public E generate(Consumer<E> consumer) {
		Assert.isTrue(false, ErrCode.METHOD_NOT_SUPPORT);
		return null;
	}

	
	public String generateKey(long playerId) {
		return GamePlayerModuleCaster.castPlayerIdTo(playerId, getValueClass());
	}

	public String genKey(){
		return getAccessor().generateKey();
	}
	
}
